package com.nutiteq.mapper.forms;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;

import com.nutiteq.MapComponent;
import com.nutiteq.MapItem;
import com.nutiteq.components.WgsPoint;

public class GoToForm extends List implements CommandListener {
  private final MapComponent mapDisplay;
  private final MapItem mapItem;

  private static int count;

  public static final Command GO_TO_COMMAND = new Command("Go to...", Command.ITEM, 0);
  private static final Command BACK = new Command("Back", Command.BACK, 0);
  private static final Command GO = new Command("Go", Command.ITEM, 0);

  private final Displayable returnTo;
  private final MIDlet midlet;

  private static final String[] PLACE_NAMES = { "Tallinn", "London", "Berlin", "New York City",
      "Barcelona", "Malaga, Spain" };
  private static final WgsPoint[] PLACE_COORDINATES = { new WgsPoint(24.75, 59.433),
      new WgsPoint(-0.115356, 51.464274), new WgsPoint(13.4167, 52.517),
      new WgsPoint(-74.0, 40.717), new WgsPoint(2.183, 41.383), new WgsPoint(-4.42, 36.72) };

  public GoToForm(final MIDlet midlet, final Displayable returnTo, final MapItem mapItem) {
    this(midlet, returnTo, null, mapItem);
  }

  public GoToForm(final MIDlet midlet, final Displayable returnTo, final MapComponent mapDisplay,
      final MapItem mapItem) {
    super("Set middle point", List.IMPLICIT);
    this.returnTo = returnTo;
    this.mapDisplay = mapDisplay;
    this.mapItem = mapItem;
    this.midlet = midlet;

    addCommand(BACK);
    addCommand(GO);
    setCommandListener(this);

    for (int i = 0; i < PLACE_NAMES.length; i++) {
      append(PLACE_NAMES[i], null);
    }
  }

  public GoToForm(final MIDlet midlet, final Displayable returnTo, final MapComponent mapDisplay) {
    this(midlet, returnTo, mapDisplay, null);
  }

  public void commandAction(final Command cmd, final Displayable d) {
    if (cmd == GO || cmd == List.SELECT_COMMAND) {
      final WgsPoint point = PLACE_COORDINATES[getSelectedIndex()];
      if (mapItem == null) {
        if (count % 2 == 0) {
          mapDisplay.setMiddlePoint(point, 8);
        } else {
          mapDisplay.setMiddlePoint(point.getLon(), point.getLat(), 8);
        }
      } else {
        if (count % 2 == 0) {
          mapItem.setMiddlePoint(point, 8);
        } else {
          mapItem.setMiddlePoint(point.getLon(), point.getLat(), 8);
        }
      }
      count++;
    }
    Display.getDisplay(midlet).setCurrent(returnTo);
  }
}
